﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObserverAndMediator
{
    /// <summary>
    /// 事件的观察者(分发者)
    /// </summary>
    public class EventDispatch : Observer
    {
        /// <summary>
        /// 单例模式
        /// </summary>
        private static volatile EventDispatch dispatch = new EventDispatch();

        /// <summary>
        /// 事件消费者
        /// </summary>
        private List<EventCustomer> customer = new List<EventCustomer>();

        /// <summary>
        /// 不允许生成新的实例
        /// </summary>
        private EventDispatch() { }

        /// <summary>
        /// 获得单例对象
        /// </summary>
        public static EventDispatch eventDispatch
        {
            get { return dispatch; }
        }

        /// <summary>
        /// 事件触发
        /// </summary>
        /// <param name="o"></param>
        /// <param name="obj"></param>
        public void update(Observable o, object obj)
        {
            //事件的源头
            Product product = (Product)obj;
            //事件
            ProductEvent events = (ProductEvent)o;
            //处理者处理，这里是中介者模式的核心，可以是很复杂的业务逻辑
            foreach (var item in customer)
            {
                //处理能力是否匹配
                foreach (var sub in item.CustomType)
                {
                    if ((int)sub == (int)events.EventType)
                    {
                        item.exec(events);
                    }
                }
            }
        }

        /// <summary>
        /// 注册事件处理者
        /// </summary>
        /// <param name="_customer"></param>
        public void registerCustomer(EventCustomer _customer)
        {
            customer.Add(_customer);
        }
    }
}
